package com.hfh.main.course.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hfh.main.common.annotate.JwtToken;
import com.hfh.main.common.method.commonMethod;
import com.hfh.main.common.resp.Result;
import com.hfh.main.course.entity.CourseListEntity;
import com.hfh.main.course.mapper.CourseListMapper;
import com.hfh.main.course.service.CourseListService;
import com.hfh.main.group.entity.GroupDetailEntity;
import com.hfh.main.group.entity.GroupEntity;
import com.hfh.main.group.service.GroupDetailService;
import com.hfh.main.group.service.GroupService;
import com.hfh.main.report.entity.DailyReportEntity;
import com.hfh.main.report.entity.WeekEntity;
import com.hfh.main.report.service.DailyReportService;
import com.hfh.main.report.service.WeekService;
import com.hfh.main.user.entity.UserEntity;
import com.hfh.main.user.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Tag(name="项目管理")
@RestController
@RequestMapping("/courseListEntity")
public class CourseListController {

    @Autowired
    private CourseListMapper courseListMapper;
    @Autowired
    private CourseListService courseListService;
    @Autowired
    private UserService userService;

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @JwtToken
    @Operation(summary = "列表-分页")
    @PostMapping("/listPageCourseList")
    public Result<?> listPageCourseList(@RequestParam Integer page, @RequestParam Integer pageSize,@RequestParam String name,@RequestParam Integer year,@RequestParam String teacherId,@RequestParam String teacherName) {
        //分页参数
        Page<CourseListEntity> rowPage = new Page(page, pageSize);
        LambdaQueryWrapper<CourseListEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CourseListEntity::getYear, year);
        if(!"undefined".equals(name) || !"undefined".equals(teacherId) || !"undefined".equals(teacherName)){
            queryWrapper.and(i->{
                if(!"undefined".equals(name)) i.or().like(CourseListEntity::getName, name); //项目名称
                if(!"undefined".equals(teacherId)) i.or().eq(CourseListEntity::getTeacherId, teacherId);
                if(!"undefined".equals(teacherName)) i.or().like(CourseListEntity::getTeacherName, teacherName);
            });
        }
        queryWrapper.orderByAsc(CourseListEntity::getNo);
        rowPage = courseListMapper.selectPage(rowPage, queryWrapper);
        return Result.success("数据请求成功", rowPage);
    }

    @JwtToken
    @Operation(summary = "查询-编号")
    @PostMapping("/selectCourseListByID/{param}")
    public Result<?> selectCourseListByID(@PathVariable @Validated String param) {
        QueryWrapper<CourseListEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(("list_id"), param);
        if (courseListService.count(wrapper) == 0) return Result.failure(200,"编号不存在", sdf.format(new Date()));
        return Result.success(supplement(courseListService.getOne(wrapper)));
    }


    /**
     * 填充 设置冗余列 指导老师名称
     * @param r
     * @return
     */
    private CourseListEntity supplement(CourseListEntity r) {
        if (r != null && r.getTeacherId() != null){
            UserEntity acc = userService.getById(r.getTeacherId());
            if(acc != null){
                r.setTeacherName(acc.getName());
            }
        }
        return r;
    }

    @JwtToken
    @Operation(summary = "查询-名称")
    @PostMapping("/selectCourseListByName/{param}")
    public Result<?> selectCourseListByName(@PathVariable @Validated String param) {
        QueryWrapper<CourseListEntity> wrapper = new QueryWrapper<>();
        wrapper.like(("list_name"), param);
        if (courseListService.count(wrapper) == 0) return Result.failure(200,"名称不存在", sdf.format(new Date()));
        return Result.success(courseListService.list(wrapper));
    }

    @JwtToken
    @Operation(summary = "保存")
    @PostMapping("/insert")
    public Result<?> insertCourseList(@RequestBody @Validated CourseListEntity entity) {
        QueryWrapper<CourseListEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(("list_id"), entity.getId());
        if (courseListService.count(wrapper) != 0) return Result.failure(200,"编号已存在", sdf.format(new Date()));
        entity.setYear(2024);
        if(entity.getTeacherId() != null && !"".equals(entity.getTeacherId())){ //知道教师不为空时设置冗余列 name
            UserEntity userEntity = userService.getById(entity.getTeacherId());
            entity.setTeacherName(userEntity.getName());
        }
        boolean b = courseListService.save(entity);
        if (b) return Result.success("保存成功", sdf.format(new Date()));
        return Result.failure(200,"保存失败", sdf.format(new Date()));
    }

    @JwtToken
    @Operation(summary = "删除")
    @PostMapping("/delete/{param}")
    public Result<?> deleteCourseList(@PathVariable @Validated String param) {
        QueryWrapper<CourseListEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(("list_id"), param);
        if (courseListService.count(wrapper) == 0) return Result.failure(200,"编号不存在", sdf.format(new Date()));
        if (courseListService.remove(wrapper)) return Result.success("删除成功", sdf.format(new Date()));
        return Result.failure(200,"删除失败", sdf.format(new Date()));
    }

    @JwtToken
    @Operation(summary = "修改")
    @PostMapping("/update")
    public Result<?> updateCourseList(@RequestBody @Validated CourseListEntity entity) {
        QueryWrapper<CourseListEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(("list_id"), entity.getId());
        if (courseListService.count(wrapper) == 0) return Result.failure(200,"编号不存在", sdf.format(new Date()));
        if(entity.getTeacherId() != null){ //知道教师不为空时设置冗余列 name
            UserEntity userEntity = userService.getById(entity.getTeacherId());
            entity.setTeacherName(userEntity.getName());
        }else{
            courseListService.updateTeacherNull(entity.getId());
        }
        if (courseListService.updateById(entity)) return Result.success("修改成功", sdf.format(new Date()));
        return Result.failure(200,"修改失败", sdf.format(new Date()));
    }

    @Operation(summary = "导出数据")
    @PostMapping("exportExcel")
    public void exportExcelCourseList(HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("Excel数据表", StandardCharsets.UTF_8).replaceAll("\\+", "%20");
        List<CourseListEntity> list = courseListService.list();
        response.setHeader("Content-disposition", "attachment;filename*=" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), CourseListEntity.class).sheet("Excel数据表").doWrite(list);
    }

    @Operation(summary = "导入数据")
    @PostMapping("/importExcel")
    public Result<?> importExcelCourseList(MultipartFile file) {
        try {
            //获取文件的输入流
            InputStream inputStream = file.getInputStream();
            List<CourseListEntity> list = EasyExcel.read(inputStream) //调用read方法
                    //注册自定义监听器，字段校验可以在监听器内实现
                    //.registerReadListener(new CourseListListener())
                    .head(CourseListEntity.class) //对应导入的实体类
                    .sheet(0) //导入数据的sheet页编号，0代表第一个sheet页，如果不填，则会导入所有sheet页的数据
                    .headRowNumber(1) //列表头行数，1代表列表头有1行，第二行开始为数据行
                    .doReadSync();//开始读Excel，返回一个List<T>集合，继续后续入库操作
            //模拟导入数据库操作
            for (CourseListEntity entity : list) {
                courseListService.saveOrUpdate(entity);
            }
            return Result.success("导入成功", sdf.format(new Date()));
        } catch (IOException exception) {
            throw new RuntimeException(exception);
        }
    }

}
